package week_3.homework;

import week_1.practice.EmptyCollectionException;
import week_2.practice.QueueADT;

//循环队列的类
public class CircularArrayQueue<T> implements QueueADT<T> {
    private final int DEFAULT_CAPACITY = 100;
    //front的值表示的是队列的首元素存储的位置，rear的值表示的是数组的下一个可用单元，count表示元素的数量。
    private int front, rear, count;
    private T[] queue;

    public CircularArrayQueue(int initialCapacity){
        front = rear =count = 0;
        queue = ((T[])(new Object[initialCapacity]));

    }

    public CircularArrayQueue(){
        queue = ((T[])(new Object[DEFAULT_CAPACITY]));
    }

    @Override
    public void enqueue(T element) {
        if(size() == queue.length)
            expandCapacity();

        queue[rear] = element;
        rear = (rear + 1) % queue.length;

        count ++;
    }
//循环数组实现扩容的代码内容
    public void expandCapacity()
    {
        T[] larger = (T[]) (new Object[queue.length*2]);
        for(int scan = 0;scan <count; scan++)
        {
            larger[scan] = queue[front];
            front = (front + 1) % queue.length;
        }
        front = 0;
        rear = count;
        queue = larger;
    }


    @Override
    public T dequeue() throws EmptyCollectionException {
        if(isEmpty())
            throw new EmptyCollectionException("queue");

        T result = queue[front];
        queue[rear] = null;
        front = (front + 1) % queue.length;

        count--;
        return result;

    }

    @Override
    public T first()
    {
        T result = queue[front];
        return result;
    }

    @Override
    public boolean isEmpty()
    {
        if (count != 0)
            return false;
        else
            return true;
    }

    @Override
    public int size()
    {
        return count;
    }

    public String toString()
    {
        String result ="";
        int temp = front;
        for(int i = 0;i < count; i++) {
            result += queue[temp] + " ";
            temp = (temp + 1) % queue.length;
        }
        return result;
    }
}

